package org.example.easybuy.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.UUID;

public class JwtUtil {
    //密钥
    public static final String SECURET="5be03772fdad3526fdf652930ee29afe1a5e5d5cfd997aabe92aee33312a741b";

    //生效时间
    public static final int TIME=30;

    //创建令牌
    public static String createToken(String loginName)
    {
        //获取的时间
        Date startTime=new Date();
        //失效的时间
        Date endTime=new Date(startTime.getTime()+TIME*60*1000);

        return JWT.create().withJWTId(UUID.randomUUID().toString())
                .withIssuedAt(startTime)
                .withExpiresAt(endTime)
                .withClaim("loginName",loginName)
                .sign(Algorithm.HMAC256(SECURET));

    }

    //根据token验证是否有效
    public static DecodedJWT verifyToken(String token) {
        DecodedJWT decodedJwt = JWT.require(Algorithm.HMAC256(SECURET)).build().verify(token);
        return decodedJwt;
    }

    //读取jwt中存储数据
    public static String getLoginName(String token) {
        return verifyToken(token).getClaim("loginName").asString();
    }

    //获取到期时间
    public static Date getExpires(String token) {
        return verifyToken(token).getExpiresAt();
    }
}
